package com.patchmanage.back.controller;


import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.patchmanage.back.entity.DepartmentGroup;
import com.patchmanage.back.entity.Inventory;
import com.patchmanage.back.entity.InventoryGroup;
import com.patchmanage.back.result.Result;
import com.patchmanage.back.service.IDepartmentGroupService;
import com.patchmanage.back.service.IInventoryGroupService;
import com.patchmanage.back.service.IInventoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author huizhao
 * @since 2021-03-27
 */
@Api(value = " 组织分组 controller", tags = {"组织分组 Api"})
@RestController
@RequestMapping("/back/group")
public class DepartmentGroupController {

    @Autowired
    public IDepartmentGroupService departmentGroupService;

    @Autowired
    public IInventoryGroupService inventoryGroupService;

    @Autowired
    public IInventoryService inventoryService;

    /**
     * 获取资产组列表
     * @param dict
     * @return
     */
    @ApiOperation(value = "获取部门组织列表接口", notes = "获取部门组织列表接口")
    @RequestMapping(value = "list", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pId", value = "pId", required = false, dataType = "Integer", paramType = "body")
    })
    public Result<JSONArray> list(@RequestBody Dict dict) {

        Integer pId = dict.getInt("pId") == null ? 0 : dict.getInt("pId");

        QueryWrapper<DepartmentGroup> queryWrapper = new QueryWrapper<DepartmentGroup>();
        queryWrapper.orderByDesc("sort");
        List<DepartmentGroup> groupList = departmentGroupService.list(queryWrapper);

        return Result.success(treeMenuList(JSONUtil.parseArray(groupList),pId));
    }

    private JSONArray treeMenuList(JSONArray menuList, int parentId) {
        JSONArray childMenu = new JSONArray();
        for (Object object : menuList) {
            JSONObject jsonMenu = JSONUtil.parseObj(object);
            int menuId = jsonMenu.getInt("id");
            int pid = jsonMenu.getInt("pId");
            if (parentId == pid) {
                JSONArray c_node = treeMenuList(menuList, menuId);
                jsonMenu.putOnce("childNode", c_node);
                childMenu.add(jsonMenu);
            }
        }
        return childMenu;
    }

    @ApiOperation(value = "新增部门组织列表接口", notes = "新增部门组织列表接口")
    @RequestMapping(value = "saveOrUpdate", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pId", value = "pId", required = false, dataType = "String", paramType = "body"),
            @ApiImplicitParam(name = "name", value = "name", required = false, dataType = "String", paramType = "body"),
            @ApiImplicitParam(name = "sort", value = "sort", required = false, dataType = "String", paramType = "body")
    })
    public Result<Boolean> saveOrUpdate(@RequestBody DepartmentGroup departmentGroup){


        /** 修改 **/
        if(departmentGroup.getId() != null && StrUtil.isNotBlank(departmentGroup.getName())){
            // 修改所有的资产分组设置
            InventoryGroup inventoryGroup = new InventoryGroup();
            inventoryGroup.setGroupName(departmentGroup.getName());
            UpdateWrapper<InventoryGroup> InvertoryGroupUpdateWrapper = new UpdateWrapper<>();
            InvertoryGroupUpdateWrapper.eq("group_id", departmentGroup.getId());
            inventoryGroupService.update(inventoryGroup, InvertoryGroupUpdateWrapper);


            // 修改所有的资产
            Inventory inventory = new Inventory();
            inventory.setDepartmentName(departmentGroup.getName());
            UpdateWrapper<Inventory> invertoryUpdateWrapper = new UpdateWrapper<>();
            invertoryUpdateWrapper.eq("group_id", departmentGroup.getId());
            inventoryService.update(inventory, invertoryUpdateWrapper);
        }
        return Result.success(departmentGroupService.saveOrUpdate(departmentGroup));
    }

    @ApiOperation(value = "删除部门组织接口", notes = "删除部门组织接口")
    @RequestMapping(value = "removeByIds", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "ids", required = true, dataType = "String", paramType = "body")
    })
    @Transactional(rollbackFor = Exception.class)
    public Result<Boolean> removeByIds(@RequestBody Dict dict){
        String id = dict.getStr("ids");
        String[] ids = id.split(",");

        List<Integer> idsList = new LinkedList<>();
        for (int i = 0; i < ids.length; i++) {
            idsList.add(Integer.parseInt(ids[i]));
        }

        if(idsList.size() > 0){
            /** 判断有没有绑定资产分组设置,有就设置为null **/
            UpdateWrapper ig = new UpdateWrapper();
            ig.set("group_name",null);
            ig.set("group_id",null);
            ig.in("group_id",idsList);
            inventoryGroupService.update(ig);

            /** 判断有没有绑定资产,有就设置为null **/
            UpdateWrapper iu = new UpdateWrapper();
            iu.set("group_id",null);
            iu.in("group_id",idsList);
            inventoryService.update(iu);

            departmentGroupService.removeByIds(idsList);
        }

        return Result.success(true);
    }

    @ApiOperation(value = "获取部门组织接口", notes = "获取部门组织接口")
    @RequestMapping(value = "getById", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "String", paramType = "body")
    })
    public Result<DepartmentGroup> getById(@RequestBody Dict dict){
        String id = dict.getStr("id");
        return Result.success(departmentGroupService.getById(id));
    }
}
